﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Castle.DynamicProxy;
using Sio.Mdm.Types;
using Sio.Mdm.Entities;
using Sio.Mdm.Server;
using IDM.Types;

namespace IDM.Web.Base
{
    public class TokenWriter : IInvokeInterceptor
    {
        private static bool IgnoreCall = false;

        #region IInvokeInterceptor Members        
        bool IInvokeInterceptor.BeforeInvoke(System.Reflection.MethodInfo method, object[] args, out object result)
        {
            result = null;
            return true;
        }

        void IInvokeInterceptor.AfterInvoke(System.Reflection.MethodInfo method, object[] args, object result, InvocationError error)
        {
            if (IgnoreCall)
            {
                return;
            }

            if (method.DeclaringType.FullName.Contains("AuthorizationService"))
            {
                return;
            }

            Token parent = EntityFactory.CreateInstance<Token>();
            Criteria criteria = new Criteria();

            criteria.Query.SetExpression(new QueryParameter("Name", method.DeclaringType.FullName));

            IgnoreCall = true;

            parent.Load(criteria);

            parent.Name = method.DeclaringType.FullName;
            parent.Update();

            Token token = EntityFactory.CreateInstance<Token>();
            
            token.Name = method.Name;
            token.Parent = parent;

            token.Update();

            IgnoreCall = false;
        }
        #endregion

        
    }
}
